package com.sdp.right.control;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.redis.RedisUtil;
import com.sdp.core.bizc.utils.SnowFlake;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.db.sys_config.service.ISysConfigService;
import com.sdp.right.entity.SysConfig;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-12-13
 */
@RestController
@RequestMapping("/SysConfigController")
public class SysConfigController {

	@Autowired
	private ISysConfigService iSysConfigService;
	
	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private RedisUtil RedisUtil;
	
	@Autowired
	private SnowFlake SnowFlake;
	
	@PostMapping(value = "/page")
	public Result<?> list(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iSysConfigService, SysConfig.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody SysConfig sysConfig) {
		if(sysConfig==null) {
			return Result.error("系统配置信息为空");
		}
		if(StringUtils.isEmpty(sysConfig.getKeyId())) {
			sysConfig.setParamCode(SnowFlake.createOrderNo());
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysConfigService, SysConfig.class, new String[] {"paramCode"}, "keyId", sysConfig, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("参数编码不能重复");
			}
			iSysConfigService.save(sysConfig);
			
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysConfigService, SysConfig.class, new String[] {"paramCode"}, "keyId", null, sysConfig, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("参数编码不能重复");
			}
			iSysConfigService.updateById(sysConfig);
			
		}
		
		//更新缓存
		RedisUtil.setMap(SysConfig.class, sysConfig.getParamCode(),sysConfig);
		return Result.ok(sysConfig);
	}
	
	
	@GetMapping(value = "/getSysConfigByCode")
	public Result<?> getSysConfigByCode(@RequestParam(name="paramCode",required=true) String paramCode) {
		SysConfig sysConfig = RedisUtil.getMap(SysConfig.class, paramCode);
		if(StringUtils.isEmpty(sysConfig)) {
			sysConfig = iSysConfigService.querySysConfigByParamCode(paramCode);
		}
		return Result.ok(sysConfig);
	}
}

